/**
 * Vite 公共配置
 */
import { defineConfig, UserConfig } from 'vite'
import path from 'node:path'
import os from 'node:os'
import getPortPkg from 'get-port'
import tsconfigPathsPkg from 'vite-tsconfig-paths';
import { createVitePlugins } from './packages/shared-config/vite.plugins'
import envConfig from './packages/shared-config/env'
import requestDomain from './packages/shared-api/src/requestLocalDomain'
// console.log('【vite.config.shared.ts ---> requestApi】]', requestApi.config)

const getPort = (getPortPkg as any).default || getPortPkg;
const tsconfigPaths = (tsconfigPathsPkg as any).default || tsconfigPathsPkg;

// ✅ 自动获取本地 IP
function getLocalIP() {
  const interfaces = os.networkInterfaces()
  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name] || []) {
      if (iface.family === 'IPv4' && !iface.internal) {
        return iface.address
      }
    }
  }
  return '127.0.0.1'
}

// ✅ 异步创建公共配置
const projectName = process.env.PROJECT_NAME;
const env = (process.env.NODE_ENV ?? 'development') as keyof typeof envConfig;
const envPathOfPackages = envConfig[env];

console.log(`【vite.config.shared.ts】🚀 工程名称: ${projectName}（环境: ${env}） (打包的环境目录：${envPathOfPackages})`)

export default async function createSharedViteConfig() {
  const host = getLocalIP()
  const port = await getPort({ port: [5173, 5300] })
  const plugins = await createVitePlugins()
  const projectRoot = process.cwd() // ✅ 子项目目录

  console.log(`【vite.config.shared.ts】🚀 本机IP地址: ${host}`)

  return defineConfig({
    root: path.resolve(__dirname, `projects/${projectName}`),
    plugins:[ ...plugins, tsconfigPaths(),],
    base: './',
    server: {
      host,
      port,
      open: true,
      // proxy: {
      //   '/api': {
      //     target: 'test.whisper.cc',
      //     changeOrigin: true,
      //     rewrite: (path) => path.replace(/^\/api/, ''),
      //   },
      // }
    },
    build: {
      outDir: path.resolve(__dirname, `dist/${envPathOfPackages}/${projectName}_${env}`),
      emptyOutDir: true,
    },
    resolve: {
      alias: {
        '@': path.resolve(projectRoot, 'src'), // ✅ 对应子项目src
        // '@': path.resolve(__dirname, `projects/${projectName}/src`),
        '@utils': path.resolve(__dirname, `packages/shared-utils/src`),
        '@api': path.resolve(__dirname, `packages/shared-api/src`),
        'vue': path.resolve(__dirname, './node_modules/vue'),
      },
    },
    define: {
      // 'process.env.VITE_API_BASE': JSON.stringify(requestApi.config)
    }
  })  
}
